package com.bawei.module_mall.http.viewModel

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.bawei.lib_mvi.base.BaseViewModel
import com.bawei.module_mall.http.intent.ShopIntent
import com.bawei.module_mall.http.repository.ShopRepository
import com.bawei.module_mall.http.state.ShopState
import com.bawei.module_mall.model.AddAddressModel
import com.bawei.module_mall.model.AddShopModel
import com.bawei.module_mall.model.RequestSearchGoodsModel
import com.bawei.module_mall.model.DeleteModel
import com.bawei.module_mall.model.ShopNumberModel
import com.bawei.module_mall.model.UpdateModel
import com.blankj.utilcode.util.ToastUtils
import com.bawei.lib_common.manager.GlobalDataManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch
import com.bawei.lib_net.msgbus.LiveDataBus
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.tencent.mmkv.MMKV
import kotlin.jvm.internal.Ref

class ShopViewModel : BaseViewModel<ShopIntent>() {
    private val repository: ShopRepository by lazy { ShopRepository() }
    private val _state = MutableStateFlow<ShopState>(ShopState.Init)
    val state: StateFlow<ShopState> = _state.asStateFlow()

    // 新增：缓存所有有详情的商品ID（字符串）
    val detailIdSet = mutableSetOf<String>()
    fun fetchDetailIds() {
        viewModelScope.launch {
            repository.getGoodsIds()
                .catch { }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200 && response.data != null) {
                        detailIdSet.clear()
                        detailIdSet.addAll(response.data)
                    }
                }
        }
    }

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect { intent ->
                when (intent) {
                    is ShopIntent.AddAddress -> addAddress(intent.addressModel)
                    is ShopIntent.GetAddress -> getAddress()
                    is ShopIntent.GetAddressCity -> getAddressCity(intent.provinceId)
                    is ShopIntent.GetAddressHome -> getAddressHome(intent.cityId)
                    is ShopIntent.GetAddressProvince -> getAddressProvince()
                    is ShopIntent.DeleteAddress -> deleteAddress(intent.id)
                    is ShopIntent.UpdateAddress -> updateAddress(intent.updateModel)
                    is ShopIntent.GetShopDetail -> getShopDetail(intent.id)
                    is ShopIntent.AddShop -> addShop(intent.addShopModel)
                    is ShopIntent.GetShop -> getShop()
                    is ShopIntent.ViewShowedGoods -> viewShowedGoods()
                    is ShopIntent.CheckGoods -> checkGoods(intent.goodsId)
                    is ShopIntent.SearchGoods -> searchGoods(intent.body)
                    is ShopIntent.ToggleGoods -> toggleGoods(intent.goodsId)
                    is ShopIntent.ToggleCollect -> toggleCollect(intent.goodsId)
                    is ShopIntent.CheckCollect -> checkCollect(intent.goodsId)
                    is ShopIntent.DeleteShop -> deleteCollect(intent.deleteModel)
                    is ShopIntent.GetCollectShop -> getCollect()
                    is ShopIntent.QueryGoods -> queryGoods(intent.body)
                    ShopIntent.GetCollectShop -> getCollect()
                    ShopIntent.GetShopNumber -> getShopNumber()
                    is ShopIntent.UpdateShopNumber -> updateShopNumber(intent.shopNumberModel)
                    is ShopIntent.GetComment -> getComment(intent.goodsId,intent.pageNum,intent.pageSize)
                    ShopIntent.GetGoodsIds -> getGoodsIds()
                }
            }
        }
    }


    private fun addAddress(addressModel: AddAddressModel) {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.addAddress(addressModel)
                .catch { e ->
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.AddAddressSuccess(null)
                    } else {
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    private fun getAddress() {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.getAddress()
                .catch { e ->
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        val addressModel = response.data
                        if (addressModel.isNullOrEmpty()) {
                            _state.value = ShopState.NoAddress // 无地址
                        } else {
                            _state.value = ShopState.GetAddressSuccess(addressModel)
                            ToastUtils.showLong("获取地址成功")
                        }
                    } else {
                        _state.value = ShopState.Error(response.msg)
                        ToastUtils.showLong("获取地址失败")
                    }
                }
        }
    }

    private fun getAddressProvince() {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.getAddressProvince()
                .catch { e ->
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.ProvincesSuccess(response.data)
                    } else {
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    private fun getAddressCity(provinceId: String) {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.getAddressCity(provinceId)
                .catch { e ->
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.CitySuccess(response.data)
                    }else{
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    private fun getAddressHome(cityId: String) {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.getAddressHome(cityId)
                .catch { e ->
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.HomeSuccess(response.data)
                    } else {
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    private fun updateAddress(updateModel: UpdateModel) {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.updateAddress(updateModel)
                .catch { e ->
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.UpdateAddressSuccess(null)
                    } else {
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    private fun deleteAddress(id: Int) {
        viewModelScope.launch {
            Log.d("ShopViewModel", "开始删除地址，ID: $id")
            _state.value = ShopState.Loading
            repository.deleteAddress(id)
                .catch { e ->
                    Log.e("ShopViewModel", "删除地址失败: ${e.message}")
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    Log.d(
                        "ShopViewModel",
                        "删除地址响应: code=${response.code}, msg=${response.msg}"
                    )
                    if (response.code == 200) {
                        Log.d("ShopViewModel", "删除地址成功，发送DeleteAddressSuccess状态")
                        _state.value = ShopState.DeleteAddressSuccess(true)
                        // 删除成功后立即刷新地址列表
                        getAddress()
                    } else {
                        Log.e("ShopViewModel", "删除地址失败: ${response.msg}")
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    private fun getShopDetail(id: Int) {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.getShopDetail(id)
                .catch { e ->
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.ShopDetailSuccess(response.data)
                    } else {
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    private fun addShop(addShopModel: AddShopModel) {
        viewModelScope.launch {
            repository.addShop(addShopModel)
                .catch { e ->
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        ToastUtils.showLong("添加购物车成功")
                        // 添加购物车成功后，更新购物车数量
                        getShop()
                        getShopNumber()
                    } else {
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    private fun getShop() {
        viewModelScope.launch {
            repository.getShop()
                .catch { e ->
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.GetShopSuccess(response.data)
                    } else {
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }


    /**
     * 橱窗
     */
    private fun viewShowedGoods() {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.viewShowedGoods()
                .catch { e ->
                    Log.e("ShopViewModel", "查看我的橱窗失败: ${e.message}")
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    Log.d(
                        "ShopViewModel",
                        "查看我的橱窗响应: code=${response.code}, msg=${response.msg}"
                    )
                    if (response.code == 200) {
                        // 假设 response.data.records 是商品列表
                        _state.value = ShopState.ViewShowedGoodsSuccess(response.data.records)
                    } else {
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    /**
     * 推荐商品
     */
    private fun searchGoods(body: RequestSearchGoodsModel) {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.searchGoods(body)
                .debounce(500)
                .catch { e ->
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.SearchGoods(response.data.records)
                    } else {
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    /**
     *搜索商品
     */
    private fun queryGoods(body: RequestSearchGoodsModel) {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.queryGoods(body)
                .catch { e ->
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.QueryGoods(response.data.records)
                    } else {
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    // 新增
    private fun checkGoods(goodsId: Int) {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.checkGoods(goodsId)
                .catch { e ->
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.CheckGoods(response.data)
                    } else {
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    private fun toggleGoods(goodsId: Int) {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.toggleGoods(goodsId)
                .catch { e ->
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.ToggleGoods(response.data)
                    } else {
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    private fun toggleCollect(goodsId: Int) {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.toggleCollect(goodsId)
                .catch { e ->
                    Log.e("ShopViewModel", "切换收藏状态失败: ${e.message}")
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        // 切换成功后，重新检查收藏状态来确定当前状态
                        Log.d("ShopViewModel", "切换收藏状态响应: code=${response.code}, msg=${response.msg}, data=${response.data}")
                        // 切换成功后，重新检查收藏状态
                        checkCollect(goodsId)
                        // 同时更新收藏列表，以更新收藏数量
                        getCollect()
                        // 这里假设接口返回true为已收藏，false为取消收藏
                        _state.value =
                            ShopState.ToggleCollectSuccess(goodsId, response.data == true)
                        Log.d(
                            "ShopViewModel",
                            "切换收藏状态响应: code=${response.code}, msg=${response.msg}"
                        )
                    } else {
                        Log.e("ShopViewModel", "切换收藏状态失败: ${response.msg}")
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    private fun checkCollect(goodsId: Int) {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.checkCollect(goodsId)
                .catch { e ->
                    Log.e("ShopViewModel", "检查商品收藏状态失败: ${e.message}")
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        // 这里假设接口返回true为已收藏，false为未收藏
                        _state.value = ShopState.CheckCollectResult(goodsId, response.data == true)
                        Log.d(
                            "ShopViewModel",
                            "检查商品收藏状态响应: code=${response.code}, msg=${response.msg}"
                        )
                    } else {
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    private fun deleteCollect(goodsId: DeleteModel) {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.deleteShop(goodsId)
                .catch { e ->
                    Log.e("ShopViewModel", "删除购物车商品失败: ${e.message}")
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.DeleteSuccess(null)
                        ToastUtils.showLong("删除购物车成功")
                        getShop()
                    } else {
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    private fun getCollect() {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.getCollect()
                .catch { e ->
                    Log.e("ShopViewModel", "获取收藏商品失败: ${e.message}")
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.GetCollectSuccess(response.data)

                        // 广播收藏数量
                        val collectCount = response.data?.records?.size ?: 0
                        LiveDataBus.with<Int>("collect_count").postValue(collectCount)
                        // 保存到本地
                        MMKV.defaultMMKV().putInt("collect_count", collectCount)
                    }else{
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }
    private fun getShopNumber(){
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.getShopNumber()
                .catch { e ->
                    Log.e("ShopViewModel", "获取购物车商品数量失败: ${e.message}")
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.GetShopNumberSuccess(response.data)
                        // 广播购物车数量
                        LiveDataBus.with<Int>("cart_count").postValue(response.data)
                        // 保存到本地
                        MMKV.defaultMMKV().putInt("cart_count", response.data ?: 0)
                    }else{
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    private fun updateShopNumber(shopNumberModel: ShopNumberModel) {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.updateShopNumber(shopNumberModel)
                .catch { e ->
                    Log.e("ShopViewModel", "更新购物车商品数量失败: ${e.message}")
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.UpdateShopNumberSuccess(response.data)
                        ToastUtils.showLong("更新购物车商品数量成功")
                        getShopNumber()
                    }else{
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    private fun getComment(goodsId:Int,pageNum:Int,pageSize: Int) {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.getComment(goodsId,pageNum,pageSize)
                .catch { e ->
                    Log.e("ShopViewModel", "获取商品评论失败: ${e.message}")
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.GetCommentSuccess(response.data)
                    }else{
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }

    private fun getGoodsIds() {
        viewModelScope.launch {
            _state.value = ShopState.Loading
            repository.getGoodsIds()
                .catch { e ->
                    Log.e("ShopViewModel", "获取商品ID失败: ${e.message}")
                    _state.value = ShopState.Error(e.message ?: "网络请求失败")
                }
                .filter { it != null }
                .collect { response ->
                    if (response.code == 200) {
                        _state.value = ShopState.GetGoodsIdsSuccess(response.data)
                    }else{
                        _state.value = ShopState.Error(response.msg)
                    }
                }
        }
    }


}